package com.mfsoft.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.mfsoft.camera.CameraApp;
import com.mfsoft.camera.R;

public class UserActions {
	public static final String API_URL = "http://ungdungviet.zz.mu/camera/note.php";
	public static final String GMAIL = "gmail";
	public static final String BIRTHDAY = "birthday";
	public static final String NICKNAME = "nickname";
	public static final String USERNAME = "username";
	public static final String GENDER = "gender";
	public static final String PASSWORD = "password";
	public static final String TYPE = "type";
	public static final String USERID = "userid";
	public static final String AVATAR = "avatar";
	public static final String PAGE = "page";
	
	private Context mContext;
	private Activity mActivity;
	public CameraApp instance;	

	public UserActions(Context context, Activity activity) {
		// TODO Auto-generated constructor stub
		mContext = context;
		mActivity = activity;		
	}

	
	
	
	public void LoginSocial(final HashMap<String, String> data) {
		Thread thread = new Thread() {
			@Override
			public void run() {
				// TODO Auto-generatedoi method stub
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(API_URL);

				try {
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					nameValuePairs.add(new BasicNameValuePair("command", "loginsocial"));
					nameValuePairs.add(new BasicNameValuePair(GMAIL, data.get(GMAIL)));
					nameValuePairs.add(new BasicNameValuePair(BIRTHDAY, data.get(BIRTHDAY)));
					nameValuePairs.add(new BasicNameValuePair(NICKNAME, data.get(NICKNAME)));
					nameValuePairs.add(new BasicNameValuePair(USERNAME, data.get(USERNAME)));
					nameValuePairs.add(new BasicNameValuePair(GENDER, data.get(GENDER)));
					nameValuePairs.add(new BasicNameValuePair(TYPE, data.get(TYPE)));
					httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

					HttpResponse response = httpClient.execute(httpPost);
					HttpEntity entity = response.getEntity();

					if (entity != null) {
						InputStream inputStream = entity.getContent();
						String result = getContent(inputStream);

						try {
							final JSONObject info = new JSONObject(result);
							JSONArray infoArray = info.getJSONArray("result");
							SharedPreferences preferences = instance.cameraModel
									.getSharedPreferences();
							for (int i = 0; i < infoArray.length(); i++) {
								JSONObject infoObject = infoArray.getJSONObject(i);
								preferences.edit().putString(GMAIL,infoObject.getString(GMAIL)).commit();
								preferences.edit().putString(USERID, infoObject.getString(USERID)).commit();
								preferences.edit().putString(BIRTHDAY, infoObject.getString(BIRTHDAY)).commit();
								preferences.edit().putString(GENDER, infoObject.getString(GENDER)).commit();
								preferences.edit().putString(USERNAME, infoObject.getString(USERNAME)).commit();
								preferences.edit().putString(TYPE, infoObject.getString(TYPE)).commit();
								preferences.edit().putString(NICKNAME, infoObject.getString(NICKNAME)).commit();
								preferences.edit().putString(AVATAR, data.get(AVATAR)).commit();
							}
							mActivity.runOnUiThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub																		
									Intent i = mActivity.getIntent();
									i.putExtra("user", "success");
									mActivity.setResult(1, i);
									mActivity.finish();
								}
							});

						} catch (JSONException e) {
							mActivity.runOnUiThread(new Runnable() {
								
								@Override
								public void run() {
									// TODO Auto-generated method stub
									showDialogError(
											mContext.getResources().getString(
													R.string.error_login_title),
											mContext.getResources().getString(
													R.string.error_login_message));
								}
							});							
						}
					}
				} catch (ClientProtocolException e) {

				} catch (IOException e) {

				}
			}
		};
		thread.start();
	}

	protected void showDialogError(String title, String message) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
		dialog.setTitle(title);
		dialog.setMessage(message);
		dialog.setPositiveButton(
				mContext.getResources().getString(R.string.button_ok),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
		dialog.show();
	}

	private static String getContent(InputStream inputStream)
			throws IOException {
		StringBuilder builder = new StringBuilder();
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(inputStream));
		String line = null;
		while ((line = bufferedReader.readLine()) != null) {
			builder.append(line).append("\n");
		}
		bufferedReader.close();
		return builder.toString().trim();
	}
	
	public Bitmap getAvatarSocial(String imageURL) {    
	    Bitmap bitmap = null;
	    Log.w("loading", "Loading Picture");	    
	    try {
	        bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
	    } catch (Exception e) {
	        Log.d("TAG", "Loading Picture FAILED");
	        e.printStackTrace();
	    }
	    return bitmap;
	}
	
}
